﻿using System;
using System.Collections.Generic;
using System.Linq;
using Coolite.Ext.Web;
using Newtonsoft.Json.Linq;
using Pap.Core.Utilities;
using Pap.Services.WorkflowEngine;
using Pap.Web.Modules.Loan.ViewModel;
using Pap.Web.Utils;
using Utils;

namespace Pap.Web.Modules.Loan.Views
{
    /// <summary>
    /// 
    /// </summary>
    public partial class ResponsibleWaitingListControl : BaseUserControl<ResponsibleWaitingListControlViewModel>
    {
        /// <summary>
        /// Handles the Load event of the Page control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack && !Ext.IsAjaxRequest)
            {
                var loans = this.ViewModel.GetLoansForCurrentResponsible(RegistryInfo.UserID);
                storeResponsibleLoans.DataSource = loans;
                storeResponsibleLoans.DataBind();
                //-------------------------------------------------------------------------
                var actionList = from action in this.ViewModel.GetAvailableDecisions()
                                 select new
                                 {
                                     DecisionID = Enums.ToString(action),
                                     DecisionName = Enums.ToString(action, GetLocalResourceObject("LanguageIndex").ToInt32()),
                                 };

                storeDecisions.DataSource = actionList;
                storeDecisions.DataBind();
            }
        }

        /// <summary>
        /// Handles the Clicked event of the BtnSubmit control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="Coolite.Ext.Web.AjaxEventArgs"/> instance containing the event data.</param>
        protected void BtnSubmit_Clicked(object sender, AjaxEventArgs e)
        {
            if (e.ExtraParams["grvLoans"] != null)
            {
                string jsonString = e.ExtraParams["grvLoans"];
                JArray jarray = JSON.Deserialize(jsonString) as JArray;

                List<Guid> loanIDs = new List<Guid>();
                List<ActionTypes> loanDecisions = new List<ActionTypes>();
                List<string> Notes = new List<string>();
                Dictionary<string, int> actionTypes = Enums.ToNameKeyPaires(typeof(ActionTypes));

                for (int i = 0; i < jarray.Count; i++)
                {
                    if (!string.IsNullOrEmpty(jarray[i]["DecisionID"].ToString().Trim('"')))
                    {
                        loanIDs.Add(jarray[i]["LoanID"].ToString().Trim('"').ToGuid());
                        loanDecisions.Add((ActionTypes)actionTypes[jarray[i]["DecisionID"].ToString().Trim('"')]);
                        if (jarray[i]["Notes"] != null)
                            Notes.Add(jarray[i]["Notes"].ToString().Trim('"'));
                        else
                            Notes.Add("");
                    }
                }


                if (loanDecisions.Count > 0)
                {
                    this.ViewModel.TakeLoanDecisions(loanIDs, Notes, loanDecisions);
                    RefreshControl();
                    if (LoansSubmitted != null)
                        LoansSubmitted(this, new AjaxEventArgs(new Coolite.Ext.Web.ParameterCollection()));
                }
            }

        }

        /// <summary>
        /// Refreshes the control.
        /// </summary>
        public void RefreshControl()
        {
            var loans = this.ViewModel.GetLoansForCurrentResponsible(RegistryInfo.UserID);
            storeResponsibleLoans.DataSource = loans;
            storeResponsibleLoans.DataBind();
        }
        /// <summary>
        /// Handles the Command event of the gvLoans control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="Coolite.Ext.Web.AjaxEventArgs"/> instance containing the event data.</param>
        protected void gvLoans_Command(object sender, AjaxEventArgs e)
        {
            switch (e.ExtraParams["CommandName"])
            {
                case "ViewLoan":
                    this.RedirectFromThisPage("Loan", "createloan", "LoanID=" + e.ExtraParams["LoanID"]);
                    break;
                case "ViewFeasabilityStudy":
                    this.RedirectFromThisPage("Loan", "feasibilitystudy", "LoanID=" + e.ExtraParams["LoanID"]);
                    break;

                case "ViewSocialResearch":
                    this.RedirectFromThisPage("Loan", "loansocialresearchdetails", "LoanID=" + e.ExtraParams["LoanID"]);
                    break;

                case "Respond":
                    this.ViewModel.TakeDecision(e.ExtraParams["LoanID"].ToGuid(), Pap.Services.WorkflowEngine.ActionTypes.Refuse);
                    break;
            }
        }

        /// <summary>
        /// Occurs when [loans submitted].
        /// </summary>
        public event EventHandler<AjaxEventArgs> LoansSubmitted;
    }
}